package com.lntea.security.des;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class LnteaDes {
	private static final String text = "lntea des";
	
	public static void main(String[] args) {
		//jdk
		jdkDES();
		
		//BouncyCastle
		BCDes();
	}
	
	public static void jdkDES(){
		try {
			//generate key
			KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
			keyGenerator.init(56);
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] encodedKey = secretKey.getEncoded();
			
			//key convert
			DESKeySpec keySpec = new DESKeySpec(encodedKey);
			SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
			SecretKey convertSecretKey = factory.generateSecret(keySpec);
			
			//encrypt key
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
			byte[] result = cipher.doFinal(text.getBytes());
			System.out.println(new String(Hex.encodeHex(result)));
			
			//decrypt key
			cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
			result = cipher.doFinal(result);
			System.out.println(new String(result));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void BCDes(){
		try {
			Security.addProvider(new BouncyCastleProvider());
			
			//generate key
			KeyGenerator keyGenerator = KeyGenerator.getInstance("DES","BC");
			keyGenerator.init(56);
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] encodedKey = secretKey.getEncoded();
			
			//key convert
			DESKeySpec keySpec = new DESKeySpec(encodedKey);
			SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
			SecretKey convertSecretKey = factory.generateSecret(keySpec);
			
			//encrypt key
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
			byte[] result = cipher.doFinal(text.getBytes());
			System.out.println(new String(Hex.encodeHex(result)));
			
			//decrypt key
			cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
			result = cipher.doFinal(result);
			System.out.println(new String(result));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
